package com.cn.ccp.action.course.select;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cn.ccp.action.BaseAction;
import com.cn.ccp.bean.CourseBean;
import com.cn.ccp.bean.CourseContentBean;
import com.cn.ccp.bean.CourseContentManageBean;
import com.cn.ccp.bean.CourseEvaluationBean;
import com.cn.ccp.bean.CourseOutlineBean;
import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.bean.StudentMarkedHistoryBean;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;

/**
 * 学生选课action
 * @author renyongcheng
 *
 */
public class SelectCourseBrowseAction extends BaseAction {
	private Logger log = Logger.getLogger(SelectCourseBrowseAction.class);
	private CourseBean course;
	private String courseId,strNextCourseDetailId,strProCourseDetailId;
	private boolean showCourseBackBtn = false ;//是否来自课程页面
	private boolean showOtherBtn = true ;
	
	private boolean showJoinStudyButton = false ;
	private List<CourseContentManageBean> courseChapterList ;//课程详细详细列表
	private List<StudentMarkedHistoryBean> markedList;//学生评价历史
	private String outline;//课程大纲
	private String courseEva;//课程考核办法
	
	private SelectItem[] courseTypeSelectItem ;
	private String selectCourseType ;
	
	private boolean showEditOutline ,showEditEvaluation ;
	private boolean initData;//初始化数据
	private boolean showOnlineTeachBackBtn = false ;//是否来自老师授课页面	
	private String[] arrayId = new String[]{};// 课程详细信息id数组
	private int curIndex = -1;//当前课程详细信息索引
	private boolean showAddOnlineTeachPages = false ;//是否来自老师添加授课页面	
	private boolean curUser = false;
	private boolean showCancelBtn = false;//显示取消课程按钮
	private Object obj = null ;
	private String chooseCourseObj = null ;
	public boolean isInitData() {
		initData();
		return initData;
	}

	public void setInitData(boolean initData) {
		this.initData = initData;
	}

	public SelectCourseBrowseAction(){
		log.info("----------SelectCourseBrowseAction()-------------------");
		resetOutlineAndEvlaSession();
	}

	private void initData(){
		resetOutlineAndEvlaSession();
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		if(varMap.get("courseId") != null && !varMap.get("courseId").equals(""))
			courseId = varMap.get("courseId") ;
		
		if(courseId != null  && !courseId.equals("")){
			course = getCourseService().getBeanById(courseId);
		}
		showJoinStudyButton = false ;
		if(varMap.get("showJoinStudyButton") != null && !varMap.get("showJoinStudyButton").equals(""))
			showJoinStudyButton = Boolean.valueOf(""+ varMap.get("showJoinStudyButton")) ;
		
		
		 
		if(varMap.get("showCourse") != null && !varMap.get("showCourse").equals(""))
			obj = varMap.get("showCourse") ;
		else 
			obj = "false";
		log.info("-------------obj = "+obj);
		showCourseBackBtn = false; 
		showOtherBtn = true ;
		if(obj != null)
			showCourseBackBtn = obj.toString().equalsIgnoreCase("true");
		if(varMap.get("onlineTeach") != null)
			chooseCourseObj = varMap.get("onlineTeach") ;
		log.info("-------------chooseCourseObj = "+chooseCourseObj);
		if(chooseCourseObj != null){
			showOnlineTeachBackBtn = chooseCourseObj.toString().equalsIgnoreCase("true");
			showCancelBtn = showOnlineTeachBackBtn;
			if(showOnlineTeachBackBtn){
				if(course.getTeacherId().equalsIgnoreCase(CCPContants.getCurrUserId())){//是自己的课程，则不显示取消按钮
					curUser = true;
					showCancelBtn = !curUser;
				}
				
				log.info("-------------showOnlineTeachBackBtn = "+showOnlineTeachBackBtn);
				showOtherBtn = false;
			}
		}
		
		Object addOnlineTeachObj = varMap.get("addOnlineTeach") ;
		log.info("-------------addOnlineTeachObj = "+addOnlineTeachObj);
		if(addOnlineTeachObj != null){
			showAddOnlineTeachPages = addOnlineTeachObj.toString().equalsIgnoreCase("true");
			if(showAddOnlineTeachPages){
				showOtherBtn = false;
				showCancelBtn = false;
			}
		}
		
		
		
		
		if(showCourseBackBtn){
			showOtherBtn = false ;
		}
		
		if(course != null && course.getId() != null){
			if(course.getImage()  != null && !"".equalsIgnoreCase(course.getImage().trim())){
				File sourseFile = null;
				if(course.getFile_path_id() !=  -1)
					sourseFile = new File(getFilePathService().findFilePathById(course.getFile_path_id()).getPath()+course.getImage());
				else
					sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + course.getImage());
				
				File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId() + File.separator);
				if(des.mkdir()){
					des.mkdirs();
				}
				des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId()  + File.separator +sourseFile.getName());
				CCPContants.copyFile(sourseFile.getPath(), des.getPath());
				course.setImage(CCPContants.getCurrUserId()+"/"+des.getName());
			}
		}
		selectCourseType = "";
		if(course != null){
			courseTypeSelectItem = null ;
			getCourseTypeSelectItem();
		}
		///
		CourseOutlineBean courseOutLineBean = getCourseService().getOutlineByCourseId(courseId);
		if(courseOutLineBean !=null && courseOutLineBean.getOutline() != null && courseOutLineBean.getOutline().endsWith(".txt")){
			showEditOutline = true;
			String savePath = getOutlineFilePath();
			savePath += courseOutLineBean.getOutline();
			log.info(savePath);
			BufferedReader reader = null;
			StringBuffer buf = new StringBuffer();
			try {
				reader = new BufferedReader(new FileReader(savePath));
				String text = null;
				while ((text = reader.readLine()) != null){
					 buf.append(text);
					 buf.append(System.getProperty("line.separator"));
				}
				outline = buf.toString();
			} catch (IOException e) {
				log.info("read outline failed : ",e);
			} finally{
				try {
					if(reader != null)
						reader.close();
				} catch (IOException e) {
				}
			} 
		}else if(courseOutLineBean !=null && courseOutLineBean.getOutline() != null){//其他文件，使用组件显示
			showEditOutline = false; 
			String savePath = getOutlineFilePath();
			savePath += courseOutLineBean.getOutline();
			String outlinePath  = CCPContants.copyOutline(savePath, courseOutLineBean.getOutline(),Contants.OUTLINE_DERECT);
			log.info("------------outlinePath = "+outlinePath);
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			session.setAttribute(CCPContants.OUTLINE_FILE_PATH, courseOutLineBean.getOutline());
		}
		log.info(courseOutLineBean);
		CourseEvaluationBean assessmentBean = getCourseService().getEvaluationByCourseId(courseId);
		if(assessmentBean != null && assessmentBean.getContents() != null && assessmentBean.getContents().endsWith(".txt")){
			showEditEvaluation = true;
			String savePath = getOutlineFilePath();
			savePath += assessmentBean.getContents();
			log.info(savePath);
		
			BufferedReader reader = null;
			StringBuffer buf = new StringBuffer();
			try {
				reader = new BufferedReader(new FileReader(savePath));
				String text = null;
				while ((text = reader.readLine()) != null){
					 buf.append(text);
					 buf.append(System.getProperty("line.separator"));
				}
				courseEva = buf.toString();
			} catch (IOException e) {
				log.info("read outline failed : ",e);
			} finally{
				try {
					if(reader != null)
						reader.close();
				} catch (IOException e) {
				}
			}
		}else if(assessmentBean != null && assessmentBean.getContents() != null){
			showEditEvaluation = false ;
			String savePath = getOutlineFilePath();
			savePath += assessmentBean.getContents();
			String evaluPath  = CCPContants.copyOutline(savePath, assessmentBean.getContents(),Contants.EVALUATION_DERECT);
			log.info("------------evaluPath = "+evaluPath);
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			session.setAttribute(CCPContants.EVALUA_FILE_PATH, assessmentBean.getContents());
		}
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.setAttribute("bbs-courseid", courseId);
	}
	
	
	private void resetOutlineAndEvlaSession(){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.removeAttribute(CCPContants.OUTLINE_FILE_PATH);
		session.removeAttribute(CCPContants.EVALUA_FILE_PATH);
		session.removeAttribute(CCPContants.FILE_TYPE);
		showEditEvaluation = true;
		showEditOutline = true;
		showOnlineTeachBackBtn = false;
		showAddOnlineTeachPages = false;
		curUser = false;
		curIndex = -1;
	}
	
	public CourseBean getCourse() {
		return course;
	}

	public String doAddStudy(){
		log.info("---------------courseId = "+courseId);
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		if(varMap.get("courseId") != null){
			courseId = varMap.get("courseId") ;
			boolean flag  = getSelectCourseService().doAddCourse(courseId, String.valueOf(CCPContants.getUserBean().getId()), CCPContants.getUserBean().getUserName());
			log.info("------------flag = "+flag);
			if(flag)
				return MAIN;
			else
				return FAILED;
		}else{
			return FAILED;
		}
	}
	
	public String showCourseContent(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String chapterId = varMap.get("chapterId");
		Object obj = varMap.get("showCourse") ;
		log.info("-------------obj = "+obj);
		if(obj != null)
			showCourseBackBtn = obj.toString().equalsIgnoreCase("true");
		CourseContentBean courseContentBean = getCourseContentService().getCourseContentBean(chapterId);
		courseId = courseContentBean.getCourse_id();
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
//		session.setAttribute(CCPContants.SWF_FILE_NAME, courseContentBean.getSection_file_url());
		int index =  courseContentBean.getSection_file_url().lastIndexOf(".");
		String fileType = courseContentBean.getSection_file_url().substring(index+1,courseContentBean.getSection_file_url().length());
		log.info("-----------fileType = "+fileType);
		
		String path = null;
		if("zip".equalsIgnoreCase(fileType)){
			
			path = "/"+ courseContentBean.getSection_file_name() + "/"+  courseContentBean.getSection_file_name()  + ".htm";
			File uFile = new File(System.getProperty("webapp.root") + "tempfile"+path);
			if(uFile.exists())
				session.setAttribute(CCPContants.VIDEO_FILE_NAME, path);
			else
				session.setAttribute(CCPContants.VIDEO_FILE_NAME, "/"+ courseContentBean.getSection_file_name() + "/"+  courseContentBean.getSection_file_name()  + ".html");
		}else {
			path = 	CCPContants.getFilePath(courseContentBean.getSection_file_url() , getFilePathService(),courseContentBean.getFilePathId(),CCPContants.getUserBean().getId());
			String filePath = CCPContants.getCurrUserId()+"/"+(new File(path)).getName();
			log.info("---------filePath = "+filePath);
			session.setAttribute(CCPContants.VIDEO_FILE_NAME, filePath);
		}
		log.info("---------path = "+path);
//		session.setAttribute(CCPContants.SWF_FILE_NAME, path);h
		
		String title = "【"+courseContentBean.getCourse_name()+"-"+courseContentBean.getChapter_title()+"-"+courseContentBean.getSection_file_name()+"】";
		if(title.length() > 30)
			title  = title.substring(0, 30) + "...";
		session.setAttribute(CCPContants.COURSE_NAME, title);
//		log.info("-----"+courseContentBean.getSection_file_url());
		
		session.setAttribute(CCPContants.FILE_TYPE, fileType);
		int len = arrayId.length;
		for(int i=0 ; i<len; i++){
			if(chapterId.equalsIgnoreCase(arrayId[i])){
				curIndex = i;
				break;
			}
		}
		
		
		if(fileType.equalsIgnoreCase("swf") && courseContentBean.getSection_file_type().equalsIgnoreCase("swf"))
			return DEFAULT_SWF_URL;
		
		
		if(fileType.equalsIgnoreCase("swf") || fileType.equalsIgnoreCase("pdf"))
			return SWF_FILE;
		else{
			
			if("flv".equalsIgnoreCase(fileType))
				return FLV_URL;
			
			if(CCPContants.DEFAULT_VEDIO_FILE_TYPE.indexOf(fileType) >= 0){
				if("ogv".equalsIgnoreCase(fileType))
					fileType = "ogg";
				session.setAttribute(CCPContants.VIDEO_FILE_TYPE, fileType);
				log.info("---------default vedio file-------");
				return DEFAULT_VEDIO_FILE;
			}else
				return VEDIO_FILE;
		}
	}
	
	
	public String goBack(){
		log.info("----goBack-----");
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Object obj = varMap.get("showCourse") ;
		Object onlineTeachObj = varMap.get("onlineTeach") ;
		boolean flag = obj.toString().equalsIgnoreCase("true");
		boolean onlineTeachFlag = onlineTeachObj.toString().equalsIgnoreCase("true");
		curIndex = -1;
		log.info("-------------showAddOnlineTeachPages = "+showAddOnlineTeachPages);
		if(showAddOnlineTeachPages)
			return "showAddOtherCourseList";
		
		if(onlineTeachFlag)
			return "onlineteachList";
		
		if(flag)
			return "goCourseList";
		else
			return MAIN;
	}
	
	public String cancelTeachOnline(){
		log.info("----cancelTeachOnline-----");
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		getCourseService().cancelSelectedCourse(varMap.get("courseId"), CCPContants.getCurrUserId());
		return "onlineteachList";
	}
	
	public String addOnlineTeach(){
		log.info("----cancelTeachOnline-----");
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		log.info("----cancelTeachOnline-----courseId = "+courseId);
		getCourseService().commitSelectedCourse(courseId,CCPContants.getCurrUserId());
		return "showAddOtherCourseList";
	}
	
	
	
	
	
	public String backToCourseList(){
		log.info("----------backToCourseList()----------");
		return "goCourseList";
	}
	
	public void courseContentTypeChange(){
		System.out.println("-------------"+selectCourseType);
	}
	
	
	public String backFromContents(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		courseId = varMap.get("courseId");
		Object obj = varMap.get("showCourse") ;
		showJoinStudyButton = false ;
		if(varMap.get("showJoinStudyButton") != null && !varMap.get("showJoinStudyButton").equals(""))
			showJoinStudyButton = Boolean.valueOf(""+ varMap.get("showJoinStudyButton")) ;
		
		curIndex = -1;
		log.info("-------------obj = "+obj);
		curUser = false;
		if(obj != null)
			showCourseBackBtn = obj.toString().equalsIgnoreCase("true");
		return MAIN;
	}

	public String getCourseId() {
		return courseId;
	}

	public void setCourseId(String courseId) {
		this.courseId = courseId;
	}
	
	public List<CourseContentManageBean> getCourseChapterList() {
		List<String> tmpList = new ArrayList<String>();
		List<CourseContentBean> zList = getCourseContentService().getCourseContentList(courseId);
		courseChapterList = new ArrayList<CourseContentManageBean>();
		CourseContentManageBean firstLevelBean = null;//章节bean
		CourseContentManageBean secondLevelBean = null;//小节节bean
		String secondTitle = "";
		for(CourseContentBean b : zList){
//			log.info(b);
			if(b.getSection_file_name() != null && !"".equalsIgnoreCase(b.getSection_file_name()))
				tmpList.add(""+b.getId());
				
			if(firstLevelBean == null){
				firstLevelBean =  addFirstLevel(b,courseChapterList,false);
			}else{
				if(b.getChapter_number().equalsIgnoreCase(firstLevelBean.getChapter_number())){//一个章节的内容
					if("0".equalsIgnoreCase(b.getStatus())){//章节下面的课程内容
						firstLevelBean.getCcList().add(b);
					}else{
						if(secondLevelBean == null){//小节bean为空
							secondLevelBean = addSecondLevel(b,false);
							firstLevelBean.getXjMList().add(secondLevelBean);
							secondTitle = b.getChapter_title();
							continue;
						}
						
						if(secondTitle.equals(b.getChapter_title())){//同一小节的课程内容
							secondLevelBean.getCcmList().add(b);
						}else{//不是一个小节的内容，则创建新的小节
							secondLevelBean = addSecondLevel(b,false);
							firstLevelBean.getXjMList().add(secondLevelBean);
							secondTitle = b.getChapter_title();
						}
						
					}
					
				}else{//不是一个章节的内容，添加一个新的章节目录
					firstLevelBean =  addFirstLevel(b,courseChapterList,false);
					secondLevelBean = null;
				}
				
			}
		}
		arrayId = new String[tmpList.size()];
		for (int i = 0; i < tmpList.size(); i++) {
			arrayId[i] = tmpList.get(i);
		}
			
		if(courseChapterList == null)
			courseChapterList = new ArrayList<CourseContentManageBean>();
		return courseChapterList;
	}

	public List<StudentMarkedHistoryBean> getMarkedList() {
		markedList =  getSelectCourseService().getMarkedList(courseId);
		return markedList;
	}

	public boolean isShowCourseBackBtn() {
		return showCourseBackBtn;
	}

	public void setShowCourseBackBtn(boolean showCourseBackBtn) {
		this.showCourseBackBtn = showCourseBackBtn;
	}

	public boolean isShowOtherBtn() {
		return showOtherBtn;
	}

	public void setShowOtherBtn(boolean showOtherBtn) {
		this.showOtherBtn = showOtherBtn;
	}
	
	public String getOutline() {
		return outline;
	}

	public void setOutline(String outline) {
		this.outline = outline;
	}

	public String getCourseEva() {
		return courseEva;
	}

	public void setCourseEva(String courseEva) {
		this.courseEva = courseEva;
	}

	public SelectItem[] getCourseTypeSelectItem() {
		if(courseTypeSelectItem == null && courseId != null  && !courseId.equals("")){
			List<String> typeList = getCourseContentService().getCourseTypleList(courseId);
			courseTypeSelectItem = new SelectItem[typeList.size()];
			for (int i = 0; i < typeList.size(); i++) {
				courseTypeSelectItem[i] = new SelectItem(typeList.get(i),typeList.get(i));	
			}
		}
		return courseTypeSelectItem;
	}

	public void setCourseTypeSelectItem(SelectItem[] courseTypeSelectItem) {
		this.courseTypeSelectItem = courseTypeSelectItem;
	}

	public String getSelectCourseType() {
		return selectCourseType;
	}

	public void setSelectCourseType(String selectCourseType) {
		this.selectCourseType = selectCourseType;
	}
	private String getOutlineFilePath(){
		FilePathBean path = getFilePathService().getFlagBean();
		String savePath = CCPContants.SYS_PATH+"files"+File.separator ;
		if(path != null){
			savePath = path.getPath() ;
		}
		return savePath;
	}

	public boolean isShowEditOutline() {
		return showEditOutline;
	}

	public void setShowEditOutline(boolean showEditOutline) {
		this.showEditOutline = showEditOutline;
	}

	public boolean isShowEditEvaluation() {
		return showEditEvaluation;
	}

	public void setShowEditEvaluation(boolean showEditEvaluation) {
		this.showEditEvaluation = showEditEvaluation;
	}

	public boolean isShowOnlineTeachBackBtn() {
		return showOnlineTeachBackBtn;
	}

	public void setShowOnlineTeachBackBtn(boolean showOnlineTeachBackBtn) {
		this.showOnlineTeachBackBtn = showOnlineTeachBackBtn;
	}

	public String getStrNextCourseDetailId() {
		if(curIndex + 1 < arrayId.length)
			strNextCourseDetailId = arrayId[curIndex +1 ];
		else
			strNextCourseDetailId = "-1";
		return strNextCourseDetailId;
	}

	public void setStrNextCourseDetailId(String strNextCourseDetailId) {
		this.strNextCourseDetailId = strNextCourseDetailId;
	}

	public String getStrProCourseDetailId() {
		if(curIndex - 1 >= 0)
			strProCourseDetailId = arrayId[curIndex - 1 ];
		else
			strProCourseDetailId = "-1";
		return strProCourseDetailId;
	}

	public void setStrProCourseDetailId(String strProCourseDetailId) {
		this.strProCourseDetailId = strProCourseDetailId;
	}

	public int getCurIndex() {
		return curIndex;
	}

	public void setCurIndex(int curIndex) {
		this.curIndex = curIndex;
	}

	public String[] getArrayId() {
		return arrayId;
	}

	public void setArrayId(String[] arrayId) {
		this.arrayId = arrayId;
	}

	public boolean isShowAddOnlineTeachPages() {
		return showAddOnlineTeachPages;
	}

	public void setShowAddOnlineTeachPages(boolean showAddOnlineTeachPages) {
		this.showAddOnlineTeachPages = showAddOnlineTeachPages;
	}

	public boolean isCurUser() {
		return curUser;
	}

	public void setCurUser(boolean curUser) {
		this.curUser = curUser;
	}

	public boolean isShowCancelBtn() {
		return showCancelBtn;
	}

	public void setShowCancelBtn(boolean showCancelBtn) {
		this.showCancelBtn = showCancelBtn;
	}

	public String getChooseCourseObj() {
		return chooseCourseObj;
	}

	public void setChooseCourseObj(String chooseCourseObj) {
		this.chooseCourseObj = chooseCourseObj;
	}

	public boolean isShowJoinStudyButton() {
		return showJoinStudyButton;
	}

	public void setShowJoinStudyButton(boolean showJoinStudyButton) {
		this.showJoinStudyButton = showJoinStudyButton;
	}

	 

	
}
